package com.lagou.servlet;

import com.lagou.bena.Admin;
import com.lagou.bena.Student;
import com.lagou.service.AdminServiceImp;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "LoginServlet", urlPatterns = "/AdminLogin")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取前端页面输入的管理员账号和密码
        String userName = request.getParameter("userName");
        String userPass = request.getParameter("userPass");

        // 创建AdminServiceImp类型的对象对前端输入的数据进行校验
        AdminServiceImp asi = new AdminServiceImp();
        Admin admin = asi.AdminLoginService(userName, userPass);

        // 登录是否成功的判断
        if (null != admin) {
            // 查询所有学生信息，得到list集合
            List<Student> students = asi.showAllService();

            // 将查询出的所有学生信息集合存入session对象中实现多个请求共享
            request.getSession().setAttribute("students", students);

            // 实现客户端的跳转
            //response.sendRedirect("stuList.jsp");
            request.getRequestDispatcher("stuList.jsp").forward(request, response);
        } else {
            // 添加登录失败的错误信息
            request.setAttribute("Error", "登录失败，账号或密码错误!");
            // 登录失败，实现服务器跳转
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");
            // 回到登录界面
            requestDispatcher.forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
